package clark.model

import java.sql.ResultSet
import model.Note
import com.trolltech.qt.gui.QTextDocument
import org.apache.log4j.Logger
import java.util.Date

object NoteTool {

    val connection = Tools.connection
    val logger = Logger.getLogger(this.getClass.getSimpleName)

    def getNotes(rs: ResultSet): List[Note] = {
        var value = List[Note]()
        while (rs.next) {
            val note = new Note(rs.getLong("id"),
                rs.getString("title"),
                new Date(rs.getTimestamp("date").getTime),
                rs.getString("catalog"), new QTextDocument {
                    setHtml(Tools.clobHandler(rs.getClob("text")))
                })
            value = value.+:(note)
        }
        value
    }

    def save(note: Note) {
        Vanguard.buildTable
        if (isExist(note)) {
            logger.info("发现笔记" + note.title + "已存在，进行更新")
            val sql = "update note set date=?,text=? where id=?"
            val ps = connection.prepareStatement(sql)
            ps.setObject(1, new java.sql.Timestamp(note.date.getTime))
            ps.setObject(2, note.content.toHtml)
            ps.setObject(3, note.id)
            ps.execute
            logger.info("更新了一条笔记；title：" + note.title)
        } else {
            val sql = "insert into note (title,catalog,date,text) values (?,?,?,?)"
            val ps = connection.prepareStatement(sql)
            ps.setObject(1, note.title)
            ps.setObject(2, note.catalog)
            ps.setObject(3, new java.sql.Timestamp(note.date.getTime))
            ps.setObject(4, note.content.toHtml)
            ps.execute
            logger.info("新增了一条笔记；title：" + note.title)
        }
    }

    def removeNote(id: Long) {
        val sql = "delete from note where id=?"
        val ps = connection.prepareStatement(sql)
        ps.setLong(1, id)
        ps.execute
        logger.info("删除了一条笔记,id:" + id)
    }

    def isExist(note: Note): Boolean = {
        val sql = "select id from note where id=?"
        val ps = connection.prepareStatement(sql)
        ps.setLong(1, note.id)
        val rs = ps.executeQuery
        var i = 0;
        Tools.Rs(rs) {
            i = i + 1
        }
        i > 0
    }

    def getLastNote: Note = {
        val sql = "select * from note as a where a.id=(select max(id) from note)"
        val ps = connection.prepareStatement(sql)
        val rs = ps.executeQuery
        val notes = getNotes(rs)
        if (notes.length > 0) {
            notes(0)
        } else {
            new Note(-1, "", new Date(), "", new QTextDocument)
        }
    }

    def main(args: Array[String]) {
        println(getLastNote)
    }
}